<template>
  <div class="home-container">
    <el-container>
      <el-header height="60px">
        <Header />
      </el-header>
      <el-main>
        <div class="toolbar">
          <el-button type="primary" @click="showAddDialog">
            <el-icon><Plus /></el-icon>添加账号
          </el-button>
        </div>
        <AccountList
          :accounts="accounts"
          @edit="handleEdit"
          @delete="handleDelete"
          @decrypt="handleDecrypt"
        />
        <AccountForm
          v-model:visible="dialogVisible"
          :account="currentAccount"
          @submit="handleSubmit"
        />
      </el-main>
    </el-container>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Plus } from '@element-plus/icons-vue'
import Header from '../components/Header.vue'
import AccountList from '../components/AccountList.vue'
import AccountForm from '../components/AccountForm.vue'
import request from '../utils/request'

const accounts = ref([])
const dialogVisible = ref(false)
const currentAccount = ref(null)

const loadAccounts = async () => {
  try {
    const res = await request.get('/api/accounts')
    if (res.data.success) {
      accounts.value = res.data.data
    }
  } catch (error) {
    ElMessage.error('加载账号列表失败')
  }
}

const showAddDialog = () => {
  currentAccount.value = null
  dialogVisible.value = true
}

const handleEdit = (account) => {
  currentAccount.value = { ...account }
  dialogVisible.value = true
}

const handleSubmit = async (account) => {
  try {
    console.log('Sending account data:', account)

    let res
    if (account.id) {
      res = await request({
        method: 'PUT',
        url: `/api/accounts/${account.id}`,
        headers: {
          'Content-Type': 'application/json'
        },
        data: {
          system_name: account.system_name,
          username: account.username,
          password: account.password,
          remark: account.remark
        }
      })
    } else {
      res = await request({
        method: 'POST',
        url: '/api/accounts',
        headers: {
          'Content-Type': 'application/json'
        },
        data: account
      })
    }

    console.log('Response:', res.data)

    if (res.data.success) {
      ElMessage.success(account.id ? '更新成功' : '添加成功')
      dialogVisible.value = false
      loadAccounts()
    } else {
      ElMessage.error(res.data.message)
    }
  } catch (error) {
    console.error('Submit error:', error)
    console.error('Request data:', account)
    ElMessage.error(error.response?.data?.message || '操作失败')
  }
}

const handleDelete = async (account) => {
  try {
    await ElMessageBox.confirm('确定要删除这个账号吗？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })

    const res = await request({
      method: 'DELETE',
      url: `/api/accounts/${account.id}`
    })

    if (res.data.success) {
      ElMessage.success('删除成功')
      loadAccounts()
    } else {
      ElMessage.error(res.data.message)
    }
  } catch (error) {
    if (error !== 'cancel') {
      console.error('Delete error:', error)
      ElMessage.error(error.response?.data?.message || '删除失败')
    }
  }
}

const handleDecrypt = async (account) => {
  try {
    const res = await request.get(`/api/accounts/${account.id}/password`)
    if (res.data.success) {
      ElMessageBox.alert(res.data.data, '密码', {
        confirmButtonText: '确定',
        callback: () => {}
      })
    }
  } catch (error) {
    ElMessage.error('解密失败')
  }
}

onMounted(loadAccounts)
</script>

<style scoped>
.home-container {
  height: 100vh;
  background-color: #f5f7fa;
}

.el-header {
  background-color: white;
  border-bottom: 1px solid #e6e6e6;
  padding: 0 20px;
}

.el-main {
  padding: 20px;
}

.toolbar {
  margin-bottom: 20px;
}
</style> 